<script setup>
import {useApi} from "../../composables/useApi"
import showTost from '@/components/toast/index.js'
import * as XLSX from "xlsx";
import moment from "moment";
import {reactive, ref} from "vue"
import ArchRightDraWaer from "@/pages/archives/components/archRightDraWaer.vue";
import ArchHeader from "@/pages/archives/components/archHeader.vue";
import {storeToRefs} from "pinia"
import {useAppStore} from "../../store/app"
import {GetAge} from "@/utils/utils.js";

const appStore = useAppStore()
const {nationArr, sexArr} = storeToRefs(appStore)
//基本数据list
let list = ref([])
let page = ref(1)
let limit = ref(20)
let total = ref(0)//总数
const selected = ref([])
let teacherList = ref([])
let queryFrom = ref({page: 1, limit: 20, real_name: '', sex: '', nation: '', birth_time: '', entry_time: ''})

const headers = [
  {
    title: "学生姓名",
    key: "real_name",
  },
  {
    title: "性别",
    key: "sex",
  },
  {
    title: "年级",
    key: "gradeTitle",
  },
  {
    title: "班级",
    key: "classTitle",
  },
  {
    title: "出生日期",
    key: "brith_time",
  },
  {
    title: "民族",
    key: "nation",
  },
  {
    title: "学生id",
    key: "studentId",
  },
  {
    title: "年龄",
    key: "age",
  },
  {
    title: "入学日期",
    key: "enter_time",
  },

  {
    title: "操作",
    key: "options",
    align: 'end',

    sortable: false,
  },
]
const brithChange = ({target})=>{
  form.value.age =  GetAge(target.value)
  console.log(form.value.age)
}
const getList = async () => {
  const {data} = await useApi('/teacher/Api.Student/index').post(queryFrom.value)
  console.log(data)
  total.value = data.value.data.total
  list.value = data.value.data.data.map(item => {
    return {
      ...item, id: item.student_id
    }
  })
}

const dialogFlag = ref(false)
// 头部表单回调
const onChange = val => {
  let data = JSON.parse(JSON.stringify(val))
  debugger
  data.birth_time = [data.birth_start_time, data.birth_end_time]
  data.enter_time = [data.entry_start_time, data.entry_end_time]
  queryFrom.value = {...queryFrom.value, ...data}
  getList()
}
const isConfirmDialogVisible = ref(false)
// 删除确认弹窗
const onHandleDelete = async (val) => {
  console.log(val)
  let ids = val.data.map(item => item.student_id).toString()
  console.log(ids)
  const {data} = await useApi('/teacher/Api.Student/delete').post({student_id: ids})
  console.log(data.value)
  if (data.value.status == 200) {
    showTost("删除成功", {duration: 3000, type: "success"})
    queryFrom.value.page = 1
    isConfirmDialogVisible.value = false
    if (val.type == 'detail') {
      dialogFlag.value = false
    }
    getList()
  }
}
const selectedItems = ref([]);

// 确认弹窗文本
const confirmMsg = ref('')

// 打开删除弹窗
const onHandleDialog = (type) => {
  if (type == 'delete') {
    console.log(selectedItems)
    if (selectedItems.value.length == 0) return
    let data = list.value.filter(item => selectedItems.value.find(val => val == item.id))
    console.log(data)
    currentOptionData.value = {
      data: data,
      type: 'list'
    }
    confirmMsg.value = `确认删除${data.map(item => item.real_name).toString()}的信息吗`
    isConfirmDialogVisible.value = true
  } else {
    addDialogFlag.value = true
  }
}
// 详情数据
const detailData = ref({})
const viewDetail = async (item) => {
  console.log(item)
  const {data} = await useApi('/teacher/Api.Student/detail').post({student_id: item.student_id})
  console.log(data)
  detailData.value = data.value.data
  dialogFlag.value = true
}
// 添加学生弹窗falg
const addDialogFlag = ref(false)
const refVForm = ref()

// 下载模板
const downLoadTemplate = async () => {
  const {data} = await useApi('/teacher/Base/downFile').post({type: 4})
  console.log(data.value)
  if (data.value.status == 200) {
    const link = document.createElement('a');
    link.href = data.value.data.fileUrl;
    link.download = data.value.data.fileName;
    link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click();

  }

}
// 新增取消回调
const resetForm = () => {
  refVForm.value?.reset()
  form.value.sex = '女'
  form.value.nation = '汉族'
  form.value.birth_time = ''
  form.value.entry_time = ''
  addDialogFlag.value = false
}


const valid = ref(false)
const form = ref({
  /**
   * 家庭地址
   */
  address: '',
  /**
   * 年龄
   */
  age: '',
  /**
   * 出生日期
   */
  brith_time: null,
  /**
   * 班级ID
   */
  class_id: null,
  /**
   * 紧急联系人
   */
  emergencyName: '',
  /**
   * 紧急联系电话
   */
  emergencyPhone: '',
  /**
   * 入学日期
   */
  enter_time: '',
  /**
   * 父亲姓名
   */
  fatherName: '',
  /**
   * 父亲电话
   */
  fatherPhone: '',
  /**
   * 年级ID
   */
  grade_id: null,
  /**
   * 身份证号
   */
  idCard: '',
  /**
   * 母亲姓名
   */
  motherName: '',
  /**
   * 母亲电话
   */
  motherPhone: '',
  /**
   * 民族，查字典表
   */
  nation: null,
  /**
   * 个人照片，url地址
   */
  phoneImg: '',
  /**
   * 体检报告，url地址
   */
  physicalFile: '',
  /**
   * 学生姓名
   */
  real_name: '',
  /**
   * 性别，男  女
   */
  sex: null,
})
const confirmAddTeacher =  (args) => {
  console.log(valid.value)

  if (!valid.value) return
  const {data} =  useApi('/teacher/Api.Student/add').post(form)
  if (data.value.status == 200) {
    refVForm.value?.reset()
    form.value.sex = ''
    form.value.nation = ''
    form.value.birth_time = ''
    form.value.entry_time = ''
    addDialogFlag.value = false
    showTost("新增成功", {duration: 3000, type: "success"})
    queryFrom.value.page = 1
    getList()
  } else {
    console.log(data.value.msg)
    // showTost("新增成功", {duration: 3000, type: "success"})

    showTost(data.value.msg, {duration: 3000, type: "error"})
  }
}
let sexList = ref(['男', '女'])
const onHandleEdit = () => {
  queryFrom.value.page = 1
  getList()
}
getList()
const required = (value, name) => !!value || `${name}为必填字段`;
const importExcelRef = ref(null)
const httpRequest = (e) => {
  let file = e.file // 文件信息
  if (!file) {
    return false
  } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    // 格式根据自己需求定义
    this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
    return false
  }
  const fileReader = new FileReader()
  fileReader.onload = (ev) => {
    try {
      const data = ev.target.result
      const workbook = XLSX.read(data, {
        // 以字符编码的方式解析
        type: 'binary',
        cellDates: true,

      })
      // 取第一张表
      console.log(workbook)
      const exlname = workbook.SheetNames[0]
      const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]) // 生成json表格内容
      console.log(exl)
      partPost(exl)
      // 将 JSON 数据挂到 data 里
      let arr = []
      exl.forEach(item => {
        arr.push(item.name)
      })
      console.log(arr)
    } catch (e) {
      console.log('error')
      return false
    }
  }
  fileReader.readAsBinaryString(file)
}
const import_page = ref(1)
const import_limit = ref(10)
const import_percent = ref(0)
const loading = ref(false)

const partPost = async (tableData) => {
  let perdata = []
  for (let i = (import_page.value - 1) * import_limit.value; i < import_page.value * import_limit.value; i++) {
    if (tableData[i]) {
      perdata.push(tableData[i])
    }
  }
  let total_page = Math.ceil(tableData.length / import_limit.value)
  import_percent.value = Math.ceil(import_page.value * 100 / total_page)
  loading.value = true
  console.log(perdata)
  perdata = perdata.map(item => {
    return {
      ...item,
      '出生日期': convertExcelDateFormat(item, '出生日期'),
      '入学日期': convertExcelDateFormat(item, '入学日期'),
    }
  })
  console.log(perdata)
  const {data} = await useApi('/teacher/Api.Student/upload').post({list: perdata})
  if (data.value.status == 200) {
    if (import_page.value <= total_page - 1) {
      import_page.value = import_page.value + 1
      partPost(data)
    } else {
      // this.dialog.importDialogstatus = false;
      showTost("导入完成", {duration: 3000, type: "success"})
      addDialogFlag.value = false
      queryFrom.value.page = 1
      getList()
      loading.value = false
    }
  }
  // importData(perdata).then(res => {
  //   if(res.status == 200){
  //     if(this.import_page <= total_page-1){
  //       this.import_page = this.import_page +1
  //       this.partPost(data)
  //     }else{
  //       this.dialog.importDialogstatus = false;
  //       this.$message({message: '导入完成', type: 'success'})
  //       this.index()
  //       this.loading = false
  //     }
  //   }
  // })
}
const afterLeave = (e) => {
  console.log(e)
}
const onChangePage = (val) => {
  queryFrom.value.page = val.page
  queryFrom.value.limit = val.limit
  getList()
}
const convertExcelDateFormat = (row, columnName) => {
  //日期转换
  var date = row[columnName]
  if (date === undefined || date === null || date === "") {
    return null;
  }
  console.log(date)
  //非时间格式问题  返回Invalid date
  let retFormat = moment(date).format('YYYY-MM-DD');
  if (retFormat === "Invalid date") {
    return retFormat;
  }
  return moment(date).add(1, 'days').format('YYYY-MM-DD')
}
const currentOptionData = ref({})
const drawaerDelete = async (val) => {
  console.log(val)
  currentOptionData.value = {
    data: [val],
    type: 'detail'
  }
  confirmMsg.value = `确认删除${val.real_name}的信息吗`
  isConfirmDialogVisible.value = true
}

// 获取年级列表开始
const gradeList = ref([])
const getGradeList = async () => {
  const {data} = await useApi('/teacher/Api.Grade/indexList').post({
    
  })
  if (data.value.status == 200) {
    console.log(data.value.data)
    gradeList.value = data.value.data
  }
}
getGradeList()
// 获取年级列表结束

// 班级不分页列表开始
const classList = ref([])
const getClassList = async (id='') => {
  const {data} = await useApi('/teacher/Api.GradeClass/indexList').post({grade_id:id})
  if (data.value.status == 200) {
    console.log(data.value.data)
    classList.value = data.value.data
  }
}
getClassList()
// 班级不分页列表结束
const gradeChange = (id)=>{
  if(id!= form.value.class_id){
    form.value.class_id = ''
  }
  getClassList(id)
}
</script>

<template>
  <div class="content">
    <arch-right-dra-waer :grade-list="gradeList" :class-list="classList" @onHandleDelete="drawaerDelete"
                         @onHandleEdit="onHandleEdit" :detailData="detailData" @update:isDrawerOpen="dialogFlag=$event"
                         :is-drawer-open="dialogFlag"></arch-right-dra-waer>
    <ConfirmDialog
      v-model:isDialogVisible="isConfirmDialogVisible"
      :handleData="currentOptionData"
      @confirm="onHandleDelete"
      :confirm-msg="confirmMsg"
      :confirmation-question="confirmMsg"
      cancel-msg="Unsubscription Cancelled!!"
    />
    <!-- 头部 -->
    <arch-header
      :grade-list="gradeList" :class-list="classList"
      title="学生信息"
      button-text="添加学生"
      @onChange="onChange"
      @onHandle="onHandleDialog"
    />

    <VDataTable
      v-model="selectedItems"
      :headers="headers"
      :items="list"
      :items-per-page="100"
      item-key="id"
      show-select
    >
      <template #item.password="{ item }">
        <div class="d-flex align-center">
          <div class="d-flex flex-column ms-3">
            {{ item.password || "******" }}
          </div>
        </div>
      </template>
      <template #item.options="{ item }">
        <div class="d-flex align-center options-right-display">
          <div class="d-flex flex-column ms-3 cursor-pointer">
            <i @click="viewDetail(item)" class="ri-menu-line"></i>
          </div>
        </div>
      </template>
    </VDataTable>
      <PaginationVue
        @onChange="onChangePage"
        :current-page="queryFrom.page"
        :page-size="queryFrom.limit"
        :total="total"
      />
    

    <!--    添加学生对话框-->
    <VDialog
      max-width="600"
      :model-value="addDialogFlag"
      :persistent="true"
      title="添加学生"
    >
      <div class="dialog-body" style="width: 600px;">
        <AppDrawerHeaderSection
          title="添加学生"
          @cancel="addDialogFlag=false"
        />
        <VDivider/>
          <PerfectScrollbar
            :options="{ wheelPropagation: false }"
            class="h-60"
          >
            <VCardText>
              <elUpload
                ref="importExcelRef"
                :limit="1"
                :show-file-list="false"
                class="uploadExcelContent"
                :http-request="httpRequest"
              >
                <VBtn
                  color="primary"
                  class="me-4 mb-5"
                >
                  <i style="font-size: 24px;margin-right: 6px" class="ri-upload-cloud-fill"></i>
                  上传Excel文件
                </VBtn>
              </elUpload>

              <VForm
                v-model="valid"
                @submit.prevent=""
                ref="refVForm"

              >
                <VRow>
                  <VCol cols="6">
                    <VTextField
                      v-model="form.real_name"
                      label="姓名"
                      :rules="[(val)=>required(val,'姓名')]"
                      placeholder="请输入姓名"
                    />
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.sex"
                      :items="sexList"
                      filterable
                      item-title="title"
                      item-value="title"
                      placeholder="请选择性别"
                      label="性别"
                      :rules="[(val)=>required(val,'性别')]"
                      class="input-width-height"
                    />

                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.grade_id"
                      :items="gradeList"
                      @update:modelValue="gradeChange"
                      item-title="title"
                      item-value="grade_id"
                      placeholder="请选择所属年级"
                      label="所属年级"
                      :rules="[(val)=>required(val,'所属年级')]"
                      class="input-width-height"
                    />

                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.class_id"
                      :items="classList"
                      item-title="title"
                      item-value="class_id"
                      placeholder="请选择所属班级"
                      label="所属班级"
                      :rules="[(val)=>required(val,'所属班级')]"
                      class="input-width-height"
                    />
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.nation"
                      :items="nationArr"
                      item-title="title"
                      item-value="title"
                      placeholder="请选择民族"
                      label="民族"
                      :rules="[(val)=>required(val,'民族')]"
                      class="input-width-height"
                    />
                  </VCol>
                  <VCol cols="6">
                    <AppDateTimePicker
                      class="input-width-height"
                      v-model="form.brith_time"
                      @change="brithChange"
                      label="出生日期"
                      placeholder="请选择出生日期"
                      :rules="[(val)=>required(val,'出生日期')]"
                    >
                      <template v-slot:label>
                        <span>出生日期</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </AppDateTimePicker>

                  </VCol>
                  <VCol cols="12">
                    <AppDateTimePicker
                      class="input-width-height"
                      v-model="form.enter_time"
                      label="入学日期"
                      placeholder="请选择入学日期"
                      :rules="[(val)=>required(val,'入学日期')]"
                    >
                      <template v-slot:label>
                        <span>入学日期</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </AppDateTimePicker>
                  </VCol>
                  <VCol cols="12">
                    <VTextField
                      v-model="form.idCard"
                      placeholder="身份证号码"
                      maxLength="18"
                      :rules="[(val)=>required(val,'身份证号码')]"
                      label="请输入身份证号码"
                    />
                  </VCol>
                  <VCol cols="12">
                    <VTextField
                      v-model="form.address"
                      label="家庭住址"
                      :rules="[(val)=>required(val,'家庭住址')]"
                      placeholder="请输入家庭住址"
                    />
                  </VCol>
                  <VDivider/>
                  <VCol cols="12">
                    <div class="d-flex justify-end">
                      <VBtn
                        color="#fff"
                        class="me-4"
                        @click.stop.prevent="downLoadTemplate"
                      >
                        下载上传模板
                      </VBtn>
                      <VBtn
                        color="#fff"
                        class="me-4"
                        @click.stop.prevent="resetForm"
                      >
                        取消
                      </VBtn>
                      <div  @click.prevent.stop="confirmAddTeacher">
                        <VBtn

                          color="primary"
                          class="me-4"
                        >
                          添加
                        </VBtn>
                      </div>
                    </div>
                  </VCol>
                </VRow>
              </VForm>
            </VCardText>
          </PerfectScrollbar>

      </div>
    </VDialog>
  </div>

</template>

<style lang="scss" scoped>

</style>
